# -*- coding: utf-8 -*-
"""
========================================================================================================================
@project : AosSanic
@file: OAClient
@Author: mengying
@email: 652044581@qq.com
@date: 2022/4/3 10:20
@desc: O2OA的流程相关接口
========================================================================================================================
"""

from config import config
import json, requests
from OAError import O2OAError
from OAClient import O2OAClient


class O2OAFlow(O2OAClient):
    """O2OA流程相关"""

    def __init__(self):
        super().__init__()

    def flowList(self, app_id, sub_name=None):
        """
        @param: app_id 应用id，只需要配置到这一层就行了
        @return: app_id是最顶层了，只需要配置到这一层就行了
        @desc: 通过主app_id获取子flow_id列表, 获取
        注: 如果sub_name不传，默认返回列表 示例：[{'name': '一户一袋', 'flow_id': 'd20982a4-9729-48bd-bd00-67ed62d50379'}]
            如果sub_name传值， 返回{'name': '一户一袋', 'flow_id': 'd20982a4-9729-48bd-bd00-67ed62d50379'} ,没有报错
        """
        url = config.O2OA_URL + "/x_processplatform_assemble_designer/jaxrs/process/application/" + app_id
        response = requests.get(url, headers=self.o2oa_headers).json()

        # 判断是否请求成功
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))

        items = [{"name": item['name'], "flow_id": item['id']} for item in response.get("data", [])]

        if sub_name:
            items = list(filter(lambda item: item['name'] == sub_name, items))
            if not items:
                raise O2OAError("没有名为sub_name的子应用")
            return items[0]

        return items

    def flowInfo(self, flow_id):
        """
        @param: flow_id 流程id
        @return: data 里面数据有分组，begin：[开始模板数据]， end：[结束模块的数据]， choiceList：[选择模块的数据]，manualList：[可调用模块的数据]， 等
        @desc： 通过流程id获取流程中每个模块的id
        """
        url = config.O2OA_URL + "/x_processplatform_assemble_designer/jaxrs/process/" + flow_id
        response = requests.get(url, headers=self.o2oa_headers).json()

        # 判断是否请求成功
        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))

        return response['data']


class O2OAFlowInstance(O2OAClient):
    """O2OA发起流程实例"""

    def start(self, flow_id, user_token, user_info):
        """
        @params: flow_id 流程模板的id
        @params: user_token 发起流程的用户token
        @params: user_info 发起流程用户信息
        @desc: 开始一个实例流程
        @return: 流程实例的work_id
        user_info = {
        identity: 洪伟杰1@101ff7b8-f5d3-40d7-a8ee-0b46f23afbae_hongweijie1@I
        latest: false  (默认)
        title: 测试判断流程-无标题  (随意没得撒子用)
        }
        注意： identity谁发起的这个流程，如果发起人和token不一致还不能发起， 信息可以由O2OAClient.user_info获得
        """
        urls = config.O2OA_URL + "/x_processplatform_assemble_surface/jaxrs/work/process/" + flow_id

        if not user_info:
            raise O2OAError("数据错误， 请跳转此处查看data的格式")

        headers = self.o2oa_headers
        headers.update({'x-token': user_token})
        response = requests.post(url=urls, data=json.dumps(user_info), headers=headers).json()
        types = response.get("type", "")

        if types != "success":
            raise O2OAError(response.get("message", ""))

        return response['data']["work"]

    def read(self, work_id, user_token=None):
        """
        @params: work_id 流程发起流程start方法生成的work_id
        @return: 返回流程的相关信息,包含发起人，当前活动节点等相关信息
        """
        url = config.O2OA_URL + "/x_processplatform_assemble_surface/jaxrs/work/v2/workorworkcompleted/" + work_id
        headers = self.o2oa_headers
        if user_token:
            headers.update({'x-token': user_token})
        response = requests.get(url=url, headers=headers).json()
        types = response.get("type", "")

        if types != "success":
            raise O2OAError(response.get("message", ""))
        return response['data']

    def skip(self, work_id, activity_id, user_token=None):
        """
        @param: work_id 发起流程得到的work_id
        @param: activity_id 调度的第几个节点,通过O2OAFlow().flowInfo获得
        @desc: 可以将流程流转直接调度到某个节点， 可以在这里做回退和跳过
        """
        url = config.O2OA_URL + "/x_processplatform_assemble_surface/jaxrs/work/v2/" + work_id + "/reroute"
        data = {
            "activity": activity_id,
            "activityType": "manual",
            "mergeWork": False,
            "manualForceTaskIdentityList": []
        }
        headers = self.o2oa_headers
        if user_token:
            headers.update({'x-token': user_token})

        response = requests.put(url=url, data=json.dumps(data), headers=headers).json()
        types = response.get("type", "")

        if types != "success":
            raise O2OAError(response.get("message", ""))

        return response['data']

    def form_id(self, work_id, user_token=None):
        """
        @param: work_id 发起流程得到的work_id
        @return: 返回form_id
        """
        url = config.O2OA_URL + "/x_processplatform_assemble_surface/jaxrs/form/v2/lookup/workorworkcompleted/" + work_id
        headers = self.o2oa_headers
        if user_token:
            headers.update({'x-token': user_token})

        response = requests.get(url=url, headers=headers).json()
        types = response.get("type", "")

        if types != "success":
            raise O2OAError(response.get("message", ""))

        return response['data']

    def form_data(self, form_id, user_token=None):
        """
        @param: form_id 表单id
        @return: 表单数据
        """
        url = config.O2OA_URL + "/x_processplatform_assemble_surface/jaxrs/form/v2/" + form_id

        headers = self.o2oa_headers
        if user_token:
            headers.update({'x-token': user_token})
        response = requests.get(url=url, headers=headers).json()
        types = response.get("type", "")

        if types != "success":
            raise O2OAError(response.get("message", ""))

        return response['data']

    def flow_data(self, work_id):
        """
        @param: work_id 发起流程得到的work_id
        @desc: 通过work_id查询流程信息
        """
        url = config.O2OA_URL + "/x_processplatform_assemble_surface/jaxrs/work/v2/workorworkcompleted/" + work_id
        response = requests.get(url=url, headers=self.o2oa_headers).json()

        types = response.get("type", "")
        if types != "success":
            raise O2OAError(response.get("message", ""))

        return response['data']


if __name__ == '__main__':
    # 点击流程配置哪里调用接口获取
    app_id = "1e58a24a-ae36-4b2a-bd1c-ac1ca06f1b69"

    # 通过app_id获取流程id列表
    print(O2OAFlow().flowList(app_id=app_id))
    'b9063e7d-42b1-429b-b8e9-95699bfc6b9d'

    # 通过流程id获取
    from rich import print_json

    print_json(json.dumps(O2OAFlow().flowInfo(flow_id='b9063e7d-42b1-429b-b8e9-95699bfc6b9d')))

    # 发起流程
    data = O2OAClient().user_login("mengying", "123456")
    user_info = {
        'identity': data["distinguishedName"],
        'latest': False,
        'title': '测试判断流程-1211223'
    }
    # print(O2OAFlowInstance().start('b9063e7d-42b1-429b-b8e9-95699bfc6b9d', user_token=data['token'], user_info=user_info))

    # print(O2OAFlowInstance().read("6e5c3393-4a7f-4f87-8dc9-513ae279a055", user_token=data['token']))

    # 流程流转
    print(O2OAFlowInstance().skip("6e5c3393-4a7f-4f87-8dc9-513ae279a055", "f3c2893b-91dc-458e-a0ea-7b7ec2919f4a",
                                  user_token=data['token']))
